export let Vue
export class Store {
    constructor(options) {
        let computed
        this._vm = new Vue({
            data: {
                state: options.state
            },
            computed
        })

        // 处理getters
        let getters = options.getters || {}
        this.getters = {}
        foreach(getters, (key, value) => {
            computed[key] = () => {
                return value(this.state)
            }
            Object.defineProperty(this.getters, key, {
                get: () => { return value(this.state) }
            })
        })
        // 
        const mutations = options.mutations || {}
        this.mutations = {}
        foreach(mutations, (key, value) => {
            this.mutations[key] = (data) => {
                value(this.state, data)
            }
        })
        // 
        const actions = options.actions || {}
        this.actions = {}
        foreach(actions, (key, value) => {
            this.actions[key] = (data) => {
                value(this, data)
            }
        })

    }

    get state() {
        return this._vm.state
    }

    commit = (name,data)=>{
        this.mutations[name](data)
    }
    dispatch = (name,data)=>{
        this.actions[name](data)
    }
}

export const install = function (_Vue) {
    Vue = _Vue
    Vue.mixin({
        beforeCreate() {
            let options = this.$options
            if (options.store) {
                this.$store = options.store
            } else {
                this.$store = options.parent && options.parent.$store
            }
        }
    }
    )
}

// utils
function foreach(obj, fn) {
    Object.keys(obj).forEach(key => fn(key, obj[key]))
}